package solution1.demo1201.demo1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient {

    private Socket socket;

    public TCPClient(String ip, int port) throws IOException {
        this.socket = new Socket(ip, port);
    }

    public void start() throws IOException {
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanner = new Scanner(System.in);
            PrintWriter writer = new PrintWriter(outputStream);
            Scanner readResponse = new Scanner(inputStream);
            while(true) {
                //1.读取用户操作
                System.out.print("-> ");
                String request = scanner.next();
                //2.将请求发送给客户端
                writer.println(request);
                writer.flush();
                //3.读取服务器响应
                String response = readResponse.next();
                System.out.println("[TCPClient] 客户端接收到服务器响应！response: " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            this.socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPClient client = new TCPClient("127.0.0.1", 9090);
        client.start();
    }

}
